{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's export the trained model to HuggingFace Hub in safetensors formats for compatibility with downstream inference engines. First, we'll define some variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_name = \"SuperCool-4x-Small\"\n",
    "checkpoint_path = \"./checkpoints/checkpoint.pt\"\n",
    "exports_path = \"./exports\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, we'll load the base model checkpoint into memory from disk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "from model import SuperCool\n",
    "\n",
    "checkpoint = torch.load(checkpoint_path, map_location=\"cpu\", weights_only=True)\n",
    "\n",
    "model = SuperCool(**checkpoint[\"model_args\"])\n",
    "\n",
    "model = torch.compile(model)\n",
    "\n",
    "model.load_state_dict(checkpoint[\"model\"])\n",
    "\n",
    "print(\"Base checkpoint loaded successfully\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we employed a weight norm reparameterization of the model weights during training, we'll remove them before exporting the model weights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.remove_weight_norms()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's export the model in HuggingFace format so that it can be used with the HuggingFace ecosystem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from os import path\n",
    "\n",
    "hf_path = path.join(exports_path, model_name)\n",
    "\n",
    "model.save_pretrained(hf_path)\n",
    "\n",
    "print(f\"Model saved to {hf_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lastly, we'll login to HuggingFaceHub and upload the model under our account."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import login\n",
    "\n",
    "login(token=\"your-api-token\")\n",
    "\n",
    "model.push_to_hub(model_name)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
